<template>
  <div class="detail-container">
    <!-- 基本信息 & 职业信息 -->
    <el-row :gutter="20">
      <!-- 左侧个人信息 -->
      <el-col :span="12">
        <el-card class="info-card">
          <div class="personal-info">
            <div class="avatar-section">
              <image-preview :src="counselor.avatar" class="profile-avatar"/>
              <h2>咨询师：{{ counselor.username }}</h2>
              <div class="meta">
                <el-rate v-model="counselor.rating" disabled></el-rate>
                <span class="reviews">({{ counselor.reviews }}条评价)</span>
              </div>
            </div>

            <el-divider/>

            <div class="contact-info">
              <div class="info-item">
                <el-icon>
                  <User/>
                </el-icon>
                <span>性别：
                  <el-tag>{{ sexMapper(counselor.sex) }}</el-tag>
                </span>
              </div>
              <div class="info-item">
                <el-icon>
                  <Phone/>
                </el-icon>
                <span>预约电话：{{ counselor.phonenumber }}</span>
              </div>
              <div class="info-item">
                <el-icon>
                  <Message/>
                </el-icon>
                <span>电子邮箱：{{ counselor.email }}</span>
              </div>
              <div class="info-item">
                <el-icon>
                  <Location/>
                </el-icon>
                <span>预约地址：{{ counselor.address }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧职业信息 -->
      <el-col :span="12">
        <el-card class="info-card">
          <div class="professional-info">
            <h3>职业信息</h3>
            <div class="info-grid">
              <div class="info-block">
                <label>专业领域</label>
                <div class="value">{{ counselor.expertise }}</div>
              </div>
              <div class="info-block full-width">
                <label>资格证书</label>
                <image-preview :src="counselor.certification" :width="100" :height="100"/>
              </div>
              <div class="info-block full-width">
                <label>个人简介</label>
                <div class="value bio">{{ counselor.bio }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预约功能模块 -->
    <el-card class="booking-card">
      <div class="booking-section">
        <h3>服务预约</h3>
        <div class="app-container">
          <!-- 添加或修改咨询预约对话框 -->
          <el-form ref="appointmentRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="预约时间" prop="scheduledTime">
              <el-date-picker clearable
                              v-model="form.scheduledTime"
                              type="datetimerange"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              start-placeholder="预约开始时间"
                              end-placeholder="预约结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="咨询方式" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio-button
                    v-for="dict in consultation_type"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="用户备注" prop="notes">
              <el-input v-model="form.notes" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
        </div>
        <div class="price-display">
          <el-button type="primary"
                     @click="submitBooking"
                     v-loading="loadingFlag">
            {{ submitText }}
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
  <!-- 预约成功弹窗 -->
  <div v-if="showSuccessDialog" class="dialog-mask">
    <div class="dialog-card">
      <!-- 标题 -->
      <h2 class="dialog-title">预约成功，等待咨询师确认</h2>

      <!-- 内容区域 -->
      <div class="dialog-content">
        <div class="info-section">
          <h3>咨询师信息</h3>
          <p>{{ consultantInfo.name }} ·
            <el-tag type="primary">{{ counselorTitlesMapper(consultantInfo.title) }}</el-tag>
          </p>
          <p>电话：{{ consultantInfo.phonenumber }} · 邮箱：{{ consultantInfo.email }}</p>
        </div>

        <div class="info-section">
          <h3>预约详情</h3>
          <p>方式：{{ consultationTypeMapper(consultantInfo.type) }}</p>
          <p>时间：{{ consultantInfo.startTime }} -- {{ consultantInfo.endTime }}</p>
          <p v-if="form.type === '1'">地点：{{ consultantInfo.location }}</p>
        </div>
      </div>

      <!-- 底部按钮 -->
      <button
          class="confirm-btn"
          @click="handleConfirm"
      >
        确认
      </button>
    </div>
  </div>
</template>


<script setup>
import {getCurrentInstance, onMounted, ref, unref} from "vue";
import {getCounselorById} from "@/api/counselor/counselor.js";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {handleBooking} from "@/api/appointment/appointment.js";
import {Location} from "@element-plus/icons-vue";
import DictTag from "@/components/DictTag/index.vue";
import {getReview} from "@/api/result/result.js";

const {proxy} = getCurrentInstance();
const {
  sys_user_sex,
  consultation_type,
  counselor_titles
} = proxy.useDict('sys_user_sex', 'consultation_type', 'counselor_titles');

// 咨询师信息
const counselor = ref({
  rating: 0,
  reviews: 0
});
const counselorId = ref();
const loadingFlag = ref(false);
const submitText = ref('提交预约');
const showSuccessDialog = ref(false);
const consultantInfo = ref({});

const data = reactive({
  form: {},
  rules: {
    scheduledTime: [
      {required: true, message: "预约时间不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "咨询方式不能为空", trigger: "change"}
    ],
    notes: [
      {required: true, message: "用户备注不能为空", trigger: "blur"}
    ],
  }
});

const {form, rules} = toRefs(data);

// 确认按钮点击事件
function handleConfirm() {
  proxy.$router.push('/');
}

//  咨询师职位字典映射
function counselorTitlesMapper(value) {
  for (let i = 0; i < counselor_titles.value.length; i++) {
    if (counselor_titles.value[i].value === value) {
      return counselor_titles.value[i].label;
    }
  }
}

//  状态字典映射
function consultationTypeMapper(value) {
  for (let i = 0; i < consultation_type.value.length; i++) {
    if (consultation_type.value[i].value === value) {
      return consultation_type.value[i].label;
    }
  }
}

//  性别字典映射
function sexMapper(value) {
  for (let i = 0; i < sys_user_sex.value.length; i++) {
    if (sys_user_sex.value[i].value === value) {
      return sys_user_sex.value[i].label;
    }
  }
}

// 预约方法
function submitBooking() {
  proxy.$refs["appointmentRef"].validate(valid => {
    if (valid) {
      loadingFlag.value = true;
      submitText.value = "提交中";
      let data = {
        counselorId: counselorId.value,
        startTime: form.value.scheduledTime[0],
        endTime: form.value.scheduledTime[1],
        type: form.value.type,
        notes: form.value.notes
      }
      handleBooking(data).then(res => {
        if (res.code === 200) {
          loadingFlag.value = false;
          submitText.value = "提交预约";
          consultantInfo.value = {
            name: counselor.value.username,
            title: counselor.value.title,
            phonenumber: counselor.value.phonenumber,
            email: counselor.value.email,
            type: data.type,
            startTime: data.startTime,
            endTime: data.endTime,
            location: counselor.value.address,
          }
          showSuccessDialog.value = true;
        }
      }).catch(error => {
        console.log("error", error)
        loadingFlag.value = false;
        submitText.value = "提交预约";
      });
    }
  })
}


// 获取咨询师信息
const getCounselor = async () => {
  try {
    const res = await getCounselorById(counselorId.value);
    if (res.data) {
      counselor.value = res.data;
    }
  } catch (error) {
    console.error('获取咨询师信息失败:', error);
  }
};

// 获取咨询师评价
const getCounselorReview = async () => {
  getReview(counselorId.value).then(res => {
    let scoreList = res.data.scoreList;
    let commentList = res.data.commentList;
    const totalScore = scoreList.reduce((sum, score) => sum + score, 0);
    counselor.value.rating = scoreList.length > 0
        ? Number((totalScore / scoreList.length).toFixed(1))
        : 0;
    counselor.value.reviews = commentList.length > 0
        ? commentList.length
        : 0;
    console.log("获取的结果",counselor.value.rating)
  })

}

onMounted(async() => {
  counselorId.value = proxy.$route.query.counselorId;
  await getCounselor();
  await getCounselorReview()
});

</script>

<style scoped lang="scss">
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-card {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  padding: 20px;
}

.dialog-title {
  color: #1890ff;
  margin-bottom: 15px;
}

.info-section {
  margin: 15px 0;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.confirm-btn {
  background: #1890ff;
  color: white;
  padding: 10px 25px;
  border-radius: 4px;
  margin-top: 15px;
  width: 100%;
}

.detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.info-card {
  margin-bottom: 20px;

  .personal-info {
    .avatar-section {
      text-align: center;

      .profile-avatar {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        margin-bottom: 15px;
      }

      .meta {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
      }
    }

    .contact-info {
      .info-item {
        display: flex;
        align-items: center;
        margin: 12px 0;
        gap: 8px;
        color: #666;
      }
    }
  }

  .professional-info {
    .info-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;

      .info-block {
        &.full-width {
          grid-column: 1 / -1;
        }

        label {
          display: block;
          color: #999;
          margin-bottom: 6px;
          font-size: 0.9em;
        }

        .value {
          font-weight: 500;

          &.bio {
            line-height: 1.6;
            white-space: pre-wrap;
          }
        }

        .cert-tag {
          margin: 4px;
          cursor: pointer;

          &:hover {
            background: #f5f7fa;
          }
        }
      }
    }
  }
}

.booking-card {
  margin-top: 20px;

  .booking-section {
    h3 {
      margin-bottom: 20px;
      color: var(--el-color-primary);
    }

    .price-display {
      margin-top: 20px;
      text-align: right;
      font-size: 18px;
      font-weight: bold;

      button {
        margin-left: 20px;
      }
    }
  }
}
</style>
